import socket from 'plus-websocket'
import config from '@/config'
import $state from '../state/index.js';
import {
	getToken
} from '@/utils/auth'


// #ifdef APP
const shortCutBadge = uni.requireNativePlugin('Ba-Shortcut-Badge')
// #endif

export default {
	socketInit() {
		let that = this
		// #ifdef MP-WEIXIN || H5
		$state.appSocket = uni.connectSocket({
			url: `${config.appWs}?token=${getToken()}`,
			complete: () => {}
		});
		// #endif

		// #ifndef MP-WEIXIN
		$state.appSocket = socket.connectSocket({
			url: `${config.appWs}?token=${getToken()}`,
			complete: () => {}
		});
		// #endif

		$state.appSocket.onOpen(function(res) {
			console.log('app连接已打开！');
			$state.socketTimer = setInterval(() => {
				$state.appSocket.send({
					data: 'ping'
				})
			}, 30000)

			if ($state.againSocketTime) {
				clearInterval($state.againSocketTime)
				$state.againSocketTime = null
			}

			that.screenMsg()
		});

		$state.appSocket.onError(function(res) {
			console.log('app 连接错误！');
			setTimeout(() => {
				that.socketInit()
			}, 5000)
		});

		$state.appSocket.onClose(function(res) {
			console.log('app 已关闭！');
			if ($state.isSocket && $state.againSocketTime == null) {
				$state.againSocketTime = setInterval(() => {
					that.socketInit()
				}, 5000)
			}
		});
	},
	close(){
		if($state.appSocket){
			$state.appSocket.close()
		}
	},
	screenMsg() {
		$state.appSocket.onMessage((msg) => {
			if (msg.data != 'pong') {
				let data = JSON.parse(msg.data)
				console.log('全局socket',data)
				if (data.msgType == 'NEW_CHAT_MSG') {
					$state.noReadNum = data.noReadMsgNum
				}

				if (data.msgType == 'NEW_FRIEND') {
					uni.setTabBarBadge({
						index: 1,
						text: '',
						color: '#F40'
					});
				}

				if (data.msgType == 'NEW_MSG_SHOW') {
					// 更新聊天列表
					$state.chatListFun.changeList(data.userChatInfo)
				}

				if (data.msgType == 'REMOVE_CHAT') {
					// 更新聊天列表
					$state.chatListFun.removeChat(data.groupId)
				}
			}
		})
	}
}